﻿var community_profile_controller = (function () {
    var communityProfileWin = $('#communities_profile'), win, imageFile, communityProfileWinSelectedImage, deleteMembersArray = '', deleteModeratorsArray = '',
        comProloader, community_data_ori, communityID, moderatorsToDelete = false, membersToDelete = false;
//    var isFirstTime=true;
    var moderatorDiv = $("#community_moderators_add"), moderatorsHtml = moderatorDiv.html(), moderatorInput, moderatorEEObj, moderatorMSObj, moderatorsIdsStr = '';
    var membersDiv = $("#community_members_add"), membersHtml = membersDiv.html(), membersInput, membersEEObj, membersMSObj, membersIdsStr = '';
    var useragent = Workport.getBrowser();
    Workport.TagFunc.setTagsAutoComplete($("#community_tags"), function () {
        comProloader.show();
    }, function () {
        comProloader.hide();
    });
    communityProfileWin.kendoWindow({width: '660px', height: '540px', title: 'Community Profile', modal: true, visible: false, resizable: false, draggable: false, actions: ["Close"],
        close: function () {
            var comInfoWinViewModel = new Object();
            if (community_profile_view_model.isChanged == true) {
                communities.refresh();
            }
            kendo.bind($("#communities_info_show"), comInfoWinViewModel);
//            kendo.bind($("#communities_info_edit"), comInfoWinViewModel);
            $('#community_members_list_table').html('');
            $('#community_moderators_list_table').html('');
            $("#community_profile_list_viewMore").hide();
            $("#community_moderators_list_viewMore").hide();
            $("#community_profile_list_collapse").hide();
            $("#community_moderators_list_collapse").hide();
            community_profile_view_model.moderatorListPN = 0;
            community_profile_view_model.memberListPN = 0;
            community_profile_controller.grey_moderator_manage_btn_click();
            community_profile_controller.grey_member_manage_btn_click();
            community_profile_controller.add_moderators_clean();
            community_profile_controller.add_members_clean();
            moderatorDiv.unbind("keyup");
            membersDiv.unbind("keyup");
            $("#communityLogo").attr("src", "imgs/CommunityDefault.png");
            communityProfileWinSelectedImage = "";
            endDatePicker.close();
            if(useragent == 'ipad'){
                $('body').unbind('touchmove');
                communityProfileWin.unbind('touchmove');
                $('#communities_profile').unbind('touchmove');
            }
        },
        open:function(){
            if(useragent == 'ipad'){
                $('body').bind('touchmove',function(event){event.preventDefault()});
                communityProfileWin.bind('touchmove',function(event){event.stopPropagation()});
                $('#communities_profile').bind('touchmove',function(event){event.stopPropagation()});  
            }
        }
    });
    win = communityProfileWin.data("kendoWindow");
    var tagsInput = $("#community_tags"), tagsInputKD = tagsInput.data('kendoAutoComplete');
    tagsInput.blur(function () {
        tagsInputKD.close();
        Workport.TagFunc.stopSearchTags();
    });
    var communitySelectImgWin = $('#community_select_img_win_body');
    communitySelectImgWin.kendoWindow({width: '512px', height: '100px', title: 'Upload photo', modal: true, visible: false, draggable: false, actions: ["Close"],
        close: function () {
            $("#community_profile_win_select_file_name").val("");
            $("#community_select_img_win_body img").attr("src", "");
            imageFile = "";
            if(useragent == 'ipad'){
                $('body').unbind('touchmove');
            }
        },
        open:function(){
            if(useragent == 'ipad'){
                $('body').bind('touchmove',function(event){event.preventDefault()});
            }
            $('#community_profile_win_img_show').hide();
        }
    });
    var endDatePicker = $("#community_enddate").kendoDatePicker({format: "MM/dd/yyyy"}).data("kendoDatePicker");
    var startDatePicker = $("#community_startdate").kendoDatePicker({format: "MM/dd/yyyy"}).data("kendoDatePicker");
    startDatePicker.enable(false);
    $("#community_startdate").attr("disabled", true);
    $("#community_startdate").css("color", '#a6a6a6');
    $("#community_enddate").attr("disabled", true);
    $("#community_enddate").css("color", '#a6a6a6');
    $("#community_type").kendoDropDownList({
        dataTextField: "text",
        dataValueField: "value",
        dataSource: [{text: "Open", value: "Open"}, {text: "Moderated", value: "Moderated"}, {text: "Restricted", value: "Restricted"}]
    });
    var combobox = $("#community_type").data("kendoDropDownList");
    $("#community_profile_select_file_field").kendoUpload({
        localization: {
            select: "Browse"
        },
        select: function (e) {
            var shareWinFileAppointType = ".jpg.jpeg.png.gif.bmp";
            //Check the file type
            if (shareWinFileAppointType.indexOf(e.files[0].extension.toLowerCase()) < 0) {
                Workport.utils.alertMsg("", "The preferred dimension of the Logo : <40*40>. The image type must be of bmp, gif, jpg, jpeg, png", function (_data) {
                });
                return;
            }
            // Check file size < 2MB
            if (e.files[0].size > (2 * 1024 * 1024)) {
                Workport.utils.alertMsg("", "The image size must be within 2MB.", function (_data) {
                });
                return;
            }
            $('#community_profile_win_select_file_name').val(e.files[0].name);
            if ($(".k-state-focused input:first").is(':hidden')) {
                $(".k-state-focused input:first").remove();
            }
            if ($("#community_profile_win_select_image ul li:last").is(':hidden')) {
                $("#community_profile_win_select_image ul li:last").remove();
            }
            var fileReader = new FileReader();
            fileReader.readAsDataURL(e.files[0].rawFile);
            $("#community_profile_win_img_show").show();
            fileReader.onload = function (e) {
                imageFile = e.target.result;
                $("#community_select_img_win_body img").attr("src", imageFile);
                communityProfileWinSelectedImage = imageFile.replace(/^.*?,/, '');
            }
        }
    });
    $("#com_pro_upload_btn").on({
        click: function (e) {
            if (!imageFile) {
                showTooltip("Must upload Community Logo to proceed.", $('#community_profile_win_select_image span'));
                return;
            }
            $("#communityLogo").attr("src", imageFile);
            communitySelectImgWin.data('kendoWindow').close();
        }
    });
    $("#com_pro_upload_cancel_btn").on({
        click: function (e) {
            communitySelectImgWin.data('kendoWindow').close();
        }
    });
    $("#communities_moderator_manage_btn").on({
        click: function (e) {
            if ($("#communities_moderator_manage_btn").children().hasClass("app_tools_d_10_10")) {
                $("#community_delete_moderators_btn").removeClass("btn_grey").addClass("btn_green");
                $("#community_add_moderators_btn").removeClass("btn_green").addClass("btn_grey");
                $("#communities_moderator_manage_btn").children().removeClass("app_tools_d_10_10").addClass("app_tools_c_10_10");
                $("#community_add_moderators_btn").show();
                $("#community_delete_moderators_btn").show();
                $("#community_addmoderators_btn").show();
                $("#community_deletemoderators_btn").hide();
                $("#community_moderators_choose").show();
                $("#community_moderators_list").hide();
                $("#community_moderators_list_viewMore").hide();
                $("#community_moderators_list_collapse").hide();
                $("#community_moderators_add").find("div:first").show();
                community_profile_view_model.moderatorListPN = 0;
                var callback = function () {
                    comProloader.hide();
                };
                community_profile_view_model.request_Community_Members(communityID, '0', false, callback);
            } else {
                var callback = function () {
                    comProloader.hide();
                    community_profile_controller.grey_moderator_manage_btn_click();
                };
                community_profile_view_model.request_Community_Members(communityID, '2', false, callback);
//            community_profile_controller.onDeleteManageBtnClicked("community_moderators_choose");
            }
        }
    });
    $("#communities_members_manage_btn").on({
        click: function (e) {
            if ($("#communities_members_manage_btn").children().hasClass("app_tools_d_10_10")) {
                $("#community_delete_members_btn").removeClass("btn_grey").addClass("btn_green");
                $("#community_add_members_btn").removeClass("btn_green").addClass("btn_grey");
                $("#communities_members_manage_btn").children().removeClass("app_tools_d_10_10").addClass("app_tools_c_10_10");
                $("#community_add_members_btn").show();
                $("#community_delete_members_btn").show();
                $("#community_addmembers_btn").show();
                $("#community_deletemembers_btn").hide();
                $("#community_members_choose").show();
                $("#community_members_list").hide();
                $("#community_profile_list_viewMore").hide();
                $("#community_profile_list_collapse").hide();
                $("#community_members_add").find("div:first").show();
                community_profile_view_model.memberListPN = 0;
                var callback = function () {
                    comProloader.hide();
                };
                community_profile_view_model.request_Community_Members(communityID, '1', false, callback);
            }
            else {
                if (community_profile_view_model.memberCount == 0) {
                    $("#community_members_list_table").html("");
                    community_profile_controller.grey_member_manage_btn_click();
                } else {
                    var callback = function () {
                        comProloader.hide();
                        community_profile_controller.grey_member_manage_btn_click();
                    };
                    community_profile_view_model.request_Community_Members(communityID, '3', false, callback);
                }
            }
        }
    });
    $("#communities_profile_rss_btn").on({
        click: function (e) {
            var callback = function () {
            };
            if ($("#communities_profile_rss_btn i").hasClass("main_common_rss_10_10")) {
                community_profile_view_model.request_rss(communityID, '0', callback);
            } else {
                community_profile_view_model.request_rss(communityID, '1', callback);
            }
        }
    });
    $("#communities_profile_manage_btn").on({
        click: function (e) {
            $("#communities_info_show").hide();
            $("#communities_info_edit").show();
            $("#communities_profile_display_upload_button").show();
            $("#communities_profile_display_upload_button").text("Upload");
            $("#community_type").parent().find('input').attr("id", "community_type_input");
        }
    });
    $("#community_edit_cancel_btn").on({
        click: function (e) {
            var data = JSON.parse(JSON.stringify(community_profile_controller.community_data_ori));
            var comInfoWinViewModel = kendo.observable(data);
            kendo.bind($("#communities_info_show"), comInfoWinViewModel);
            kendo.bind($("#communities_info_edit"), comInfoWinViewModel);
            $("#community_pro_tags").html(community_profile_controller.tagsClickable(data.CommunityTags));
            $("#communityLogo").attr("src", data.CommunityLogoPathUrl);
            $("#communities_info_show").show();
            $("#communities_info_edit").hide();
            $("#communities_profile_display_upload_button").hide();
        }
    });
    $("#community_delete_moderators_btn").on({
        click: function (e) {
            $("#community_moderators_add").find("div:first").hide();
            $("#community_add_moderators_btn").removeClass("btn_grey").addClass("btn_green");
            $("#community_delete_moderators_btn").removeClass("btn_green").addClass("btn_grey");
            $("#community_addmoderators_btn").hide();
            $("#community_deletemoderators_btn").show();
            community_profile_controller.onDeleteManageBtnClicked("community_moderators_choose");
        }
    });
    $("#community_add_moderators_btn").on({
        click: function (e) {
            $("#community_moderators_add").find("div:first").show();
            community_profile_controller.onAddManageBtnClicked("community_moderators_choose");
            $("#community_delete_moderators_btn").removeClass("btn_grey").addClass("btn_green");
            $("#community_add_moderators_btn").removeClass("btn_green").addClass("btn_grey");
            $("#community_addmoderators_btn").show();
            $("#community_deletemoderators_btn").hide();
            moderatorsToDelete = false;
        }
    });
    $("#community_deletemoderators_save_btn").on({
        click: function (e) {
            community_profile_controller.deleteMembersSaved("1", "2")
        }
    });
    $("#community_addmoderators_add_btn").on({
        click: function (e) {
            community_profile_controller.onSaveBtnClick('1');
        }
    });
    $("#community_delete_members_btn").on({
        click: function (e) {
            $("#community_members_add").find("div:first").hide();
            $("#community_add_members_btn").removeClass("btn_grey").addClass("btn_green");
            $("#community_delete_members_btn").removeClass("btn_green").addClass("btn_grey");
            $("#community_addmembers_btn").hide();
            $("#community_deletemembers_btn").show();
            community_profile_controller.onDeleteManageBtnClicked("community_members_choose");
        }
    });
    $("#community_add_members_btn").on({
        click: function (e) {
            $("#community_members_add").find("div:first").show();
            community_profile_controller.onAddManageBtnClicked("community_members_choose");
            $("#community_delete_members_btn").removeClass("btn_grey").addClass("btn_green");
            $("#community_add_members_btn").removeClass("btn_green").addClass("btn_grey");
            $("#community_addmembers_btn").show();
            $("#community_deletemembers_btn").hide();
            membersToDelete = false;
        }
    });
    $("#community_deletemembers_save_btn").on({
        click: function (e) {
            if (community_profile_view_model.memberCount == 0) {
                community_profile_controller.grey_member_manage_btn_click();
            } else {
                community_profile_controller.deleteMembersSaved("0", "3");
            }
        }
    });
    $("#community_addmembers_add_btn").on({
        click: function (e) {
            community_profile_controller.onSaveBtnClick('0');
        }
    });
    $("#community_members_back_btn").on({
        click: function (e) {
            community_profile_controller.grey_member_manage_btn_click();
        }
    });

    function getModeratorIdsStr(idsStr) {
        moderatorsIdsStr = idsStr;
    }

    function getMemberIdsStr(idsStr) {
        membersIdsStr = idsStr;
    }

    function showTooltip(errMsg, elem, location) {
        var _location = "right";
        if (location) {
            _location = location;
        }
        ;
        elem.kendoTooltip({
            content: errMsg,
            position: _location,
            hide: function () {
                community_profile_controller.clean_tooltip(elem)
            }
        });
        elem.data('kendoTooltip').show();
    }

    return {
        profileCopyURL: function (params) {
            community_profile_controller.initProfilePage(params.communityId);
        },
        initProfilePage: function (commId) {
            $('#community_members_list_table').html('');
            $('#community_moderators_list_table').html('');
            moderatorDiv.html(moderatorsHtml);
            moderatorInput = $("#communities_win_moderators_input");
            moderatorEEObj = {ids: [], names: [], idsStr: "", idsStrLen: 250};
            moderatorMSObj = {msElem: moderatorInput, msDiv: moderatorDiv};
            Workport.MultiSelectFunc.createMultiSelect(moderatorMSObj, moderatorEEObj, getModeratorIdsStr, function () {
                comProloader.show();
            }, function () {
                comProloader.hide();
            });

            membersDiv.html(membersHtml);
            membersInput = $("#communities_win_members_input");
            membersEEObj = {ids: [], names: [], idsStr: "", idsStrLen: 250};
            membersMSObj = {msElem: membersInput, msDiv: membersDiv}
            Workport.MultiSelectFunc.createMultiSelect(membersMSObj, membersEEObj, getMemberIdsStr, function () {
                comProloader.show();
            }, function () {
                comProloader.hide();
            });
            $('#communities_profile_wnd_title').html('<span class="text-overflow left">Community Profile</span><i id="skipicon" class="main_smartstream_u_8_8 wp_ml_5 wp_mt_3 community_hand" title="View Community Stream"></i>');
            $('#skipicon').on({
                click: function (e) {
                    var id = $("#community_id").val();
                    var name = $("#community_name").val();
                    $('#communities_profile').data("kendoWindow").close();
                    var callback = function () {
                        communities.refresh();
                    }
                    community_smartstream.exportInterface(id, name, callback, community_profile_view_model.enableJoin);
                }
            });
            communityID = $.trim(commId);
            community_profile_controller.hide_manage_icon();
            win.center();
            win.open();
            comProloader = new Workport.Loader($('#communities_profile'), { text: 'Loading', position: 'center', imgColor: 'black', textCSS: {'color': 'black'} });
            $('#communities_profile_win_body').hide();
//            comProloader.setOptions({textCSS:{'display':'block'}});
            comProloader.show();
            var callback = function () {
                $('#communities_profile_win_body').show();
                comProloader.setOptions({textCSS:{'color':'white'}});
                comProloader.setOptions({imgColor:'white'});
                comProloader.setOptions({boxCSS:{'background-color':'black','opacity':'1'}});
                comProloader.hide();
                if(useragent == 'ipad'){
                    $('#communities_profile_win_body').css('height','auto');
                    $('#communities_profile_win_body').css('overflow-y','scroll');
                }else{
                    $('#communities_profile_win_body').slimScroll({
                        distance: '0px',
                        disableFadeOut: true,
                        height: 'auto'
                    });
                }
            };
            community_profile_view_model.request_Community(commId, false, callback);
            Workport.LocationManager.addURL('CommProfileWindow', community_profile_controller.profileCopyURL);
            Workport.LocationManager.setFullURL(communityProfileWin.data('kendoWindow'), 'CommProfileWindow', {communityId: commId});
        },
        community_info_save_button_clicked: function () {
            var errFlag = false, communityInfo = {};
            communityInfo.communityId = $("#community_id").val();
            communityInfo.status = $("#community_status").val();
            communityInfo.logo = $("#communityLogo").attr("src");
            communityInfo.name = $.trim($("#community_name").val());
            communityInfo.nickname = $.trim($("#community_nick_name").val());
            communityInfo.type = $.trim(combobox.value());
            communityInfo.description = $.trim($("#community_description").val());
            communityInfo.tags = $.trim($("#community_tags").val());
            communityInfo.startDate = community_profile_controller.getTimeByLocalTimeZone($("#community_startdate").val());
            communityInfo.endDate = community_profile_controller.getTimeByLocalTimeZone($("#community_enddate").val());
            communityInfo.members = [];
            communityInfo.managers = [];
            //logo check
            if (communityProfileWinSelectedImage != undefined) {
                communityInfo.logo = communityProfileWinSelectedImage;
            }
            if($("#communityLogo").attr("src") == "imgs/CommunityDefault.png"){
                if (!communityInfo.logo) {
                    showTooltip("Must upload Community Logo to proceed.", $('#communities_profile_display_upload_button'));
                    errFlag = true;
                }
            }
            else if(communityProfileWinSelectedImage==undefined){
                communityInfo.logo='';
            }

            //name check
            if (communityInfo.name == "") {
                showTooltip("Must enter Community Name to proceed.", $('#community_name'));
                errFlag = true;
            }
            else if (community_profile_controller.do_check_input(communityInfo.name, 1)) {
                showTooltip("Must enter alpha-numeric characters only.", $('#community_name'));
                errFlag = true;
            }
            else {
                if (community_profile_view_model.communityName != $('#community_name').val()) {
                    Workport.CommunityAPI.exist(function (data) {
                        if (data.IsNameAvailableForCreation == false) {
                            showTooltip("Community Name already exists. Please try a different name.", $('#community_name'));
                            errFlag = true;
                        }
                    }, {name: communityInfo.name, type: 1, sync: true});
                }
            }
            //nick name check
            if (communityInfo.nickname == "") {
                showTooltip("Must enter Community Nickname to proceed.", $('#community_nick_name'));
                errFlag = true;
            }
            else if (community_profile_controller.do_check_input(communityInfo.nickname, 1)) {
                showTooltip("Must enter alpha-numeric characters only.", $('#community_nick_name'));
                errFlag = true;
            }
            //description check
            if (communityInfo.description == "") {
                showTooltip("Must enter Community Description to proceed.", $('#community_description'));
                errFlag = true;
            }else if (communityInfo.description.length > 500) {
                showTooltip("Community Description must be within 500 characters.", $('#community_description'));
                errFlag = true;
            }
            //tags check
            if (communityInfo.tags == "") {
                showTooltip("Must enter Tags to proceed.", $('#community_tags'));
                errFlag = true;
            }
            else if (community_profile_controller.do_check_input(communityInfo.tags, 2)) {
                showTooltip("The allowed characters are Alpha-numeric # @ $ % &", $('#community_tags'));
                errFlag = true;
            }
            else if (communityInfo.tags.length > 255) {
                showTooltip("Tags must be less than <255> characters.", $('#community_tags'));
                errFlag = true;
            }
            //date check
            var dateVal = new Date(startDatePicker.value());
            var start = kendo.toString(dateVal, "MM/dd/yyyy");
            dateVal = new Date(endDatePicker.value());
            var end = kendo.toString(dateVal, "MM/dd/yyyy");
            var elem = $("#community_enddate").parent().find(".k-i-calendar");
            if (end == '01/01/1970') {
                showTooltip("Must enter end date to proceed.", elem);
                errFlag = true;
            }
            else if (Date.parse(start, "MM/dd/yyyy") >= Date.parse(end, "MM/dd/yyyy")) {
                showTooltip("End date must be greater than start date.", elem);
                errFlag = true;
            }
            $("#community_startdate").parent().parent().css("width", "100px");
            $("#community_enddate").parent().parent().css("width", "100px");
            if (errFlag) {
                return;
            }
            community_profile_controller.community_data_ori.CommunityName = communityInfo.name;
            community_profile_controller.community_data_ori.CommunityNickName = communityInfo.nickname;
            community_profile_controller.community_data_ori.CommunityTags = communityInfo.tags;
            community_profile_controller.community_data_ori.CommunityType = communityInfo.type;
            community_profile_controller.community_data_ori.CommunityEndDate = end;
            community_profile_controller.community_data_ori.CommunityDescription = communityInfo.description;
            community_profile_controller.community_data_ori.CommunityLogoPathUrl = $("#communityLogo").attr("src");
            var dataTmp = JSON.parse(JSON.stringify(community_profile_controller.community_data_ori));
            var comInfoWinViewModel = kendo.observable(dataTmp);
            kendo.bind($("#communities_info_show"), comInfoWinViewModel);
            kendo.bind($("#communities_info_edit"), comInfoWinViewModel);
            Workport.CommunityAPI.editCommunity(function (data) {
                if (data.ResponseCode != 'WP1008') {
                    Workport.utils.alertMsg("", data.ResponseMessage, function (_data) {
                    });
                }else{
                    community_profile_view_model.isChanged = true;
                    community_profile_view_model.communityName = $("#community_name").val();
                    headerHtmlFunc.getCommunitys();
                    $("#communities_info_show").show();
                    $("#communities_info_edit").hide();
                    $("#communities_profile_display_upload_button").hide();
                }
            }, communityInfo);
        },
        getTimeByLocalTimeZone: function (date) {
            var originalDate = new Date(date);
            var localOffset = originalDate.getTimezoneOffset() * 60000;
            var localDate = originalDate.getTime() - localOffset;
            return kendo.toString(new Date(localDate), 'G');
        },
        onModeratorImgClicked: function (element) {
            if ($(element).parent().find(".manage-add").length > 0) {
                $(element).parent().find(".manage-add").remove();
            }
            else {
                $(element).before('<strong class="manage-add k-upload-status" style="left:-10px; top:-3px; line-height:0;">' +
                    '<button type="button" class="k-button k-button-bare k-upload-action">' +
                    '<span class="k-icon main_calendar_q_10_10" title="Add"></span>' +
                    '</button>' +
                    '</strong>');
            }
        },
        onAddManageBtnClicked: function (id) {
            $("#" + id).find(".manage-delete").remove();
//            $("#" + id).find("img").attr("onclick", "");
        },
        onDeleteManageBtnClicked: function (id) {
            if ('community_moderators_choose' == id) {
                moderatorsToDelete = true;
            } else if ('community_members_choose' == id) {
                membersToDelete = true;
            }
            else {
                moderatorsToDelete = false;
                membersToDelete = false;
            }
            $("#" + id).find(".manage-add").remove();
//            $("#" + id).find("img").attr("onclick", "");
            $("#" + id).find("img").before('<strong class="manage-delete k-upload-status"><button type="button" class="k-button k-button-bare k-upload-action"><span class="delete_icon k-icon" title="Remove" ></span></button></strong>');
            $("#" + id).find("button").attr('onclick', 'community_profile_controller.onDeleteIconClicked(this,"' + id + '")');
            $("#" + id).find("li").each(function () {
                var personId = $(this).find(".userid").text();
                if ($.trim(personId) != "") {
                    $(this).find("button").attr("id", "community_delete_icon_" + personId);
                }
            });
        },
        onDeleteIconClicked: function (element, id) {
            var user = $.trim($(element).parentsUntil($("li")).parent().find(".userid").text());
            var isManager = '0';
            var type = '1';
            if ('community_moderators_choose' == id) {
                isManager = '1';
                type = '0';
            }
            if (type == '0') {
                if (community_profile_view_model.moderatorCount == 1) {
                    Workport.utils.alertMsg("", "Community must have at least one Moderator", function (_data) {
                    });
                    return;
                }
                else {
                    community_profile_view_model.moderatorCount = community_profile_view_model.moderatorCount - 1;
                    deleteModeratorsArray = deleteModeratorsArray + user + ';';
                }
            }
            else {
                deleteMembersArray = deleteMembersArray + user + ';';
            }
            $(element).parentsUntil($("li")).parent().remove();
        },
        onSaveBtnClick: function (isManager) {
            var callback = function () {
                community_profile_view_model.isChanged = true;
                var callback_refresh = function () {
                    comProloader.hide();
                    if(isManager == '1'){
                        community_profile_controller.grey_moderator_manage_btn_click();
                    }else if(isManager == '0'){
                        community_profile_controller.grey_member_manage_btn_click();
                    }
                };

                if ('1' == isManager) {
                    community_profile_view_model.request_Community_Members(communityID, '2', false, callback_refresh);
                    community_profile_controller.add_moderators_clean();
                }
                else {
                    community_profile_view_model.request_Community_Members(communityID, '3', false, callback_refresh);
                    community_profile_controller.add_members_clean();
                }

            }
            if ('1' == isManager) {
                var elem = $("#community_moderators_add").find("div:first");
                if ($.trim(moderatorsIdsStr) == "") {
                    showTooltip("Must Enter at least one moderator.", elem);
                    return;
                }
                community_profile_view_model.request_edit_Community_Members(communityID, moderatorsIdsStr, '0', isManager, false, callback);

            } else {
                var elem = $("#community_members_add").find("div:first");
                if ($.trim(membersIdsStr) == "") {
                    showTooltip("Must Enter at least one member.", elem);
                    return;
                }
                community_profile_view_model.request_edit_Community_Members(communityID, membersIdsStr, '0', isManager, false, callback);
            }
        },
        head_portrait_button_clicked: function (buttonText) {
            if (buttonText == "Join") {
                var callback = function () {
                };
                community_profile_view_model.request_join_leave_status(communityID, '0', callback);
            } else if (buttonText == "Leave") {
                var callback = function () {
                };
                community_profile_view_model.request_join_leave_status(communityID, '1', callback);
            }
            else if (buttonText == "Upload") {
                communitySelectImgWin.data("kendoWindow").center();
                communitySelectImgWin.data("kendoWindow").open();
            }
        },
        grey_moderator_manage_btn_click: function () {
            $("#community_add_moderators_btn").hide();
            $("#community_delete_moderators_btn").hide();
            $("#community_addmoderators_btn").hide();
            $("#community_deletemoderators_btn").hide();
            $("#communities_moderator_manage_btn").children().removeClass("app_tools_c_10_10").addClass("app_tools_d_10_10");
            $("#community_moderators_list").show();
            $("#community_moderators_choose").hide();
            $("#community_moderators_choose_viewMore").hide();
            $("#community_moderators_choose_collapse").hide();
            $("#community_moderators_choose_table").html('');
            moderatorsToDelete = false;
            community_profile_view_model.moderatorChoosePN = 0;
            deleteModeratorsArray = '';
        },
        grey_member_manage_btn_click: function () {
            $("#community_add_members_btn").hide();
            $("#community_delete_members_btn").hide();
            $("#community_addmembers_btn").hide();
            $("#community_deletemembers_btn").hide();
            $("#communities_members_manage_btn").children().removeClass("app_tools_c_10_10").addClass("app_tools_d_10_10");
            $("#community_members_list").show();
            $("#community_members_choose").hide();
            $("#community_profile_choose_viewMore").hide();
            $("#community_profile_choose_collapse").hide();
            $("#community_members_choose_table").html('');
            membersToDelete = false;
            community_profile_view_model.memberChoosePN = 0;
            deleteMembersArray = '';
        },
        add_moderators_clean: function () {
            $("#communities_win_moderators_input").data("kendoMultiSelect").setDataSource([]);
            $("#communities_win_moderators_input").data("kendoMultiSelect").value([]);
            moderatorEEObj.names = [];
            moderatorsIdsStr = "";
        },
        add_members_clean: function () {
            $("#communities_win_members_input").data("kendoMultiSelect").setDataSource([]);
            $("#communities_win_members_input").data("kendoMultiSelect").value([]);
            membersEEObj.names = [];
            membersIdsStr = "";
        },
        show_manage_icon: function () {
            $("#communities_profile_manage_btn").show();
            $("#communities_moderator_manage_btn").show();
            $("#communities_members_manage_btn").show();
        },
        hide_manage_icon: function () {
            $("#communities_profile_manage_btn").hide();
            $("#communities_moderator_manage_btn").hide();
            $("#communities_members_manage_btn").hide();
        },
        do_check_input: function (input, type) {
            var reg1 = /^[A-Za-z0-9\s]+$/; //Alpha-numeric characters only
            var reg2 = /^[0-9a-zA-Z#@$%&,\s]+$/ // The allowed characters are Alpha-numeric # @ $ % &
            var haveerror = false;
            if (type == 1) {
                if (!reg1.test(input)) {
                    haveerror = true;
                }
            } else if (type == 2) {
                if (!reg2.test(input)) {
                    haveerror = true;
                }
            }
            return haveerror;
        },
        clean_tooltip: function (obj) {
            obj.data('kendoTooltip').destroy();
            obj.removeAttr('data-role');
            obj.removeAttr('aria-describedby');
        },
        render: function (_data, tablename, isMore) {
            var rowTmpl = $.trim($('#community_list_content').html());
            var tpl = kendo.template(rowTmpl, {useWithBlock: false});
            var arr = new Array();
            arr.push('<div style="margin-top: 10px;"><ul class="k-upload-files k-reset" style="display: block;">');
            $.map(_data, function (_elem) {
                arr.push(tpl(_elem));
            });
            arr.push('</ul></div>');
            if (!isMore) {
                $(tablename).html('');
            }
            $(arr.join('')).appendTo(tablename);
            arr.length = 0;
        },
        deleteMembersSaved: function (isManager, type) {
            var callback_refresh = function () {
                comProloader.hide();
                if(isManager == '1'){
                    community_profile_controller.grey_moderator_manage_btn_click();
                }else if(isManager == '0'){
                    community_profile_controller.grey_member_manage_btn_click();
                }
//                community_profile_controller.onDeleteManageBtnClicked(id);
            };
            var strMem = "";
            if (isManager == '1') {
                strMem = deleteModeratorsArray.substring(0, deleteModeratorsArray.length - 1);
            } else if (isManager == '0') {
                strMem = deleteMembersArray.substring(0, deleteMembersArray.length - 1);
            }
            var callback = function () {
                var arrayMemLength = strMem.split(";").length;
                if (isManager == '1') {
                    if (deleteModeratorsArray.indexOf(WP_USER_ID) >= 0) {
                        community_profile_controller.cancelEdit();
                    }
//                    community_profile_view_model.moderatorCount = community_profile_view_model.moderatorCount-arrayMemLength;
                    deleteModeratorsArray = '';
                } else if (isManager == '0') {
                    community_profile_view_model.memberCount = community_profile_view_model.memberCount - arrayMemLength;
                    deleteMembersArray = '';
                }
                community_profile_view_model.isChanged = true;
                community_profile_view_model.request_Community_Members(communityID, type, false, callback_refresh);
            }
            community_profile_view_model.request_edit_Community_Members(communityID, strMem, '1', isManager, false, callback);
        },
        viewMore: function (type, collapseId, tableid) {
//            if(isFirstTime){
            var callback = function () {
                comProloader.hide();
                if (moderatorsToDelete == true) {
                    community_profile_controller.onDeleteManageBtnClicked("community_moderators_choose");
                } else if (membersToDelete == true) {
                    community_profile_controller.onDeleteManageBtnClicked("community_members_choose");
                }
                if (community_profile_view_model.responseCode == 'WP1001') {
                    $("#" + collapseId).hide();
                }
                else {
                    $("#" + collapseId).show();
                }
            };
            community_profile_view_model.request_Community_Members(communityID, type, true, callback);
//            }
//            else{
//                var obj = $('#'+tableid+'>div>ul>li');
//                obj.each(function(i){
//                        $(this).show();
//                })
//            }
        },
        collapse: function (tableid, viewmoreid, collapseid) {
            var obj = $('#' + tableid + '>div>ul>li');
            obj.each(function (i) {
                if (i >= 9) {
                    $(this).hide();
                }
            });
            if (tableid == 'community_moderators_list_table') {
                community_profile_view_model.moderatorListPN = 0;
            } else if (tableid == 'community_moderators_choose_table') {
                community_profile_view_model.moderatorChoosePN = 0;
            } else if (tableid == 'community_members_list_table') {
                community_profile_view_model.memberListPN = 0;
            } else if (tableid == 'community_members_choose_table') {
                community_profile_view_model.memberChoosePN = 0;
            }
            $("#" + viewmoreid).show();
            $("#" + collapseid).hide();
        },
        tagsClickable: function (tags) {
            var strArray = (tags + '').split(",");
            var innerHtml = '';
            for (var i = 0; i < strArray.length; i++) {
                var tempHtml = '<span class="community_hand" onclick="community_profile_controller.closeWindow();communities.tagsClick('+"'"+strArray[i]+"'"+')">' + strArray[i] +'</span>';
//                var tempHtml = '<span class="" onclick="console.log(' + "'" + strArray[i] + "'" + ')">' + strArray[i] + '</span>';
                if (i != strArray.length - 1) {
                    tempHtml += ',';
                }
                innerHtml += tempHtml;
            }
            return innerHtml;
        },
        globalLoading: function () {
            comProloader.show();
        },
        loaderHide: function() {
            comProloader.hide();
        },
        closeWindow:function(){
            $('#communities_profile').data("kendoWindow").close();
        },
        cancelEdit:function(){
            community_profile_controller.hide_manage_icon();
            community_profile_controller.grey_moderator_manage_btn_click();
            community_profile_controller.grey_member_manage_btn_click();
            var data = JSON.parse(JSON.stringify(community_profile_controller.community_data_ori));
            var comInfoWinViewModel = kendo.observable(data);
            kendo.bind($("#communities_info_show"), comInfoWinViewModel);
            kendo.bind($("#communities_info_edit"), comInfoWinViewModel);
            $("#community_pro_tags").html(community_profile_controller.tagsClickable(data.CommunityTags));
            $("#communityLogo").attr("src", data.CommunityLogoPathUrl);
            $("#communities_info_show").show();
            $("#communities_info_edit").hide();
            $("#communities_profile_display_upload_button").hide();
        }
    }
})();
Workport.LocationManager.addURL('CommProfileWindow', community_profile_controller.profileCopyURL);
var community_profile_view_model = kendo.observable({
    requestArray: [],
    callbackArray: [],
    availableArray: [],
    communityName: "",
    enableJoin: false,
    enableLeave: false,
    enableSetting: false,
    isSubscribed: false,
    moderatorCount: 0,
    memberCount: 0,
    isChanged: false,
    comUserInfoWinViewModel: [],
    pageNumber: 0,
    responseCode: '',
    memberListPN: 0,
    memberChoosePN: 0,
    moderatorListPN: 0,
    moderatorChoosePN: 0,
    request_Community: function (communityID, isMore, controllerCB) {
        var parameter = {
            communityId: ''
        };
        parameter.communityId = communityID;
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);
        var cb = function (data) {
            var index = $.inArray(req, community_profile_view_model.requestArray);
            if (index >= 0) {
                var avail = community_profile_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    $("#communities_info_show").show();
                    $("#communities_info_edit").hide();
                    $("#communities_profile_display_upload_button").show();
                    $("#communities_profile_display_upload_button").attr("disabled", false);
                    $("#communities_profile_display_upload_button").removeClass("k-state-disabled");
                    $("#communities_profile_display_upload_button").css("color", '#FFF');
                    $("#skipicon").show();
                    community_profile_view_model.isChanged = false;
                    community_profile_view_model.enableJoin = data.CommunityUserDetails[0].UserStatus.EnableJoin;
                    this.enableJoin = data.CommunityUserDetails[0].UserStatus.EnableJoin;
                    this.enableLeave = data.CommunityUserDetails[0].UserStatus.EnableLeave;
                    this.enableSetting = data.CommunityUserDetails[0].UserStatus.EnableSetting;
                    this.isSubscribed = data.CommunityUserDetails[0].UserStatus.isSubscribed;
                    this.pendingStatus = data.CommunityUserDetails[0].UserStatus.PendingStatus;
                    if (this.enableSetting == true) {
                        community_profile_controller.show_manage_icon();
                        $("#communities_profile_display_upload_button").hide();
                    }
                    else if (this.enableJoin == true) {
                        $("#communities_profile_display_upload_button").text("Join");
                        if (data.CommunityUserDetails[0].CommunityType == "Moderated") {
                            $("#skipicon").hide();
                        }
                    }
                    else if (this.enableLeave == true) {
                        $("#communities_profile_display_upload_button").text("Leave");
                    }
                    else if (this.pendingStatus == true) {
                        $("#communities_profile_display_upload_button").show();
                        $("#communities_profile_display_upload_button").text("Leave");
                        $("#communities_profile_display_upload_button").css("color", '').addClass("k-state-disabled");
                        $("#communities_profile_display_upload_button").attr("disabled", true);
//                        $("#communities_profile_display_upload_button").css({'color': '#a6a6a6'});
                        if (data.CommunityUserDetails[0].CommunityType == "Moderated") {
                            $("#skipicon").hide();
                        }
                    }
                    else if ((this.enableLeave == false) && (this.enableJoin == false) && (this.enableSetting == false) && (this.pendingStatus == false)) {
                        $("#communities_profile_display_upload_button").hide();
                        community_profile_controller.hide_manage_icon();
                    }
                    if (this.isSubscribed == true) {
                        $("#communities_profile_rss_btn i").removeClass("main_common_rssGrey_10_10").addClass("main_common_rss_10_10").attr('title','Unsubscribe');
                    }else{
                        $("#communities_profile_rss_btn i").removeClass("main_common_rss_10_10").addClass("main_common_rssGrey_10_10").attr('title','Subscribe');
                    }
                    if(data.CommunityUserDetails[0].CommunityContributorCount>20){
                        $("#community_profile_list_viewMore").show();
                        community_profile_view_model.memberListPN = 20-9;
                    }
                    if(data.CommunityUserDetails[0].CommunityModeratorCount>20){
                        $("#community_moderators_list_viewMore").show();
                        community_profile_view_model.moderatorListPN = 20-9;
                    }
                    data.CommunityUserDetails[0].CommunityMembersCount += " Member(s)";
                    var comInfoWinViewModel = kendo.observable(data.CommunityUserDetails[0]);
                    $("#communityLogo").attr("src", comInfoWinViewModel.CommunityLogoPathUrl);
                    $("#community_id").val(comInfoWinViewModel.CommunityID);
                    community_profile_view_model.communityName = comInfoWinViewModel.CommunityName;
                    $("#community_status").val(comInfoWinViewModel.CommunityStatus);
                    var dateArray = new Array();
                    dateArray = comInfoWinViewModel.CommunityStartDate.split(" ");
                    comInfoWinViewModel.CommunityStartDate = dateArray[0];
                    kendo.bind($("#communities_info_show"), comInfoWinViewModel);
                    kendo.bind($("#communities_info_edit"), comInfoWinViewModel);
                    $("#community_pro_tags").html(community_profile_controller.tagsClickable(data.CommunityUserDetails[0].CommunityTags));
                    community_profile_controller.render(comInfoWinViewModel.CommunityModerator, '#community_moderators_list_table', true);
                    community_profile_controller.render(comInfoWinViewModel.CommunityContributor, '#community_members_list_table', true);
                    $("#communities_info_show").find("div:first").attr("title", comInfoWinViewModel.CommunityName);
                    var realCB = community_profile_view_model.callbackArray[index];
                    realCB();
                    community_profile_controller.community_data_ori = JSON.parse(JSON.stringify(comInfoWinViewModel));
                    break;
                }
                community_profile_view_model.requestArray.splice(index, 1);
                community_profile_view_model.callbackArray.splice(index, 1);
                community_profile_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.CommunityAPI.getCommunityDetail(cb, parameter);
    },
    request_Community_Members: function (communityID, type, isMore, controllerCB) {
        if (isMore && "0" == type) {
            this.moderatorChoosePN = this.moderatorChoosePN + 9;
            this.pageNumber = this.moderatorChoosePN;
        }else if (isMore && "1" == type) {
            this.memberChoosePN = this.memberChoosePN + 9;
            this.pageNumber = this.memberChoosePN;
        }else if (isMore && "2" == type) {
            this.moderatorListPN = this.moderatorListPN + 9;
            this.pageNumber = this.moderatorListPN;
        }else if (isMore && "3" == type) {
            this.memberListPN = this.memberListPN + 9;
            this.pageNumber = this.memberListPN;
        }else {
            this.pageNumber = 0;
        }
        var parameter = {
            communityId: '',
            pageSize: 9,
            pagePosition: this.pageNumber,
            type: ''
        };
        parameter.communityId = communityID;
        parameter.type = type;
        if (type == "2" || type == "4") {
            parameter.type = "0";
        } else if (type == "3") {
            parameter.type = "1";
        }
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);
        var cb = function (data) {
            var index = $.inArray(req, community_profile_view_model.requestArray);
            if (index >= 0) {
                var avail = community_profile_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    community_profile_view_model.responseCode = data.ResponseCode;
                    if (data.ResponseCode == "WP1003" || data.UserDetails == null) {
                        community_profile_controller.loaderHide();
                        break;
                    }
                    if (data.ResponseCode == "WP1001") {
                        if (type == '1') {
                            $("#community_profile_choose_viewMore").show();
                        }
                        else if (type == '3') {
                            $("#community_profile_list_viewMore").show();
                        }
                        else if (type == '0') {
                            $("#community_moderators_choose_viewMore").show();
                        }
                        else if (type == '2') {
                            $("#community_moderators_list_viewMore").show();
                        }
                    }
                    else {
                        if(type == '2'){
                            $("#community_moderators_list_viewMore").hide();
                        }else if(type == '3'){
                            $("#community_profile_list_viewMore").hide();
                        }else if(type == '0'){
                            $("#community_moderators_choose_viewMore").hide();
                        }else if(type == '1'){
                            $("#community_profile_choose_viewMore").hide();
                        }
                    }
                    this.comUserInfoWinViewModel = data.UserDetails;
                    if (type == '0') {
                        community_profile_controller.render(this.comUserInfoWinViewModel, '#community_moderators_choose_table', isMore);
                        if (isMore) {
                            community_profile_view_model.moderatorCount += this.comUserInfoWinViewModel.length;
                        } else {
                            community_profile_view_model.moderatorCount = this.comUserInfoWinViewModel.length;
                        }
                    }
                    else if (type == '1') {
                        community_profile_controller.render(this.comUserInfoWinViewModel, '#community_members_choose_table', isMore);
                        if (isMore) {
                            community_profile_view_model.memberCount += this.comUserInfoWinViewModel.length;
                        } else {
                            community_profile_view_model.memberCount = this.comUserInfoWinViewModel.length;
                        }
                    } else if (type == '2') {
                        community_profile_controller.render(this.comUserInfoWinViewModel, '#community_moderators_list_table', isMore);
                    } else if (type == '3') {
                        if (this.comUserInfoWinViewModel != null) {
                            community_profile_controller.render(this.comUserInfoWinViewModel, '#community_members_list_table', isMore);
                        }
                        else {
                            $("#community_members_list_table").html("");
                        }
                    }
                    var realCB = community_profile_view_model.callbackArray[index];
                    realCB();
                    break;
                }
                community_profile_view_model.requestArray.splice(index, 1);
                community_profile_view_model.callbackArray.splice(index, 1);
                community_profile_view_model.availableArray.splice(index, 1);
            }
        };
        community_profile_controller.globalLoading();
        Workport.CommunityAPI.getCommunityMemberShip(cb, parameter);
    },
    request_edit_Community_Members: function (communityID, user, action, isManager, isMore, controllerCB) {
        var userContents = new Array();
        if (user == "") {
            return;
        }
        else {
            var strMem = user.split(";");
            for (var i = 0; i < strMem.length; i++) {
                userContents.push({user: strMem[i], action: action, isManager: (isManager == 1 ? true : false) });
            }
            var parameter = {
                communityId: '',
                users: userContents
            };
            parameter.communityId = communityID;
            var req = JSON.stringify(parameter);
            this.requestArray.push(req);
            this.availableArray.push(true);
            this.callbackArray.push(controllerCB);
            var cb = function (data) {
                var index = $.inArray(req, community_profile_view_model.requestArray);
                if (index >= 0) {
                    var avail = community_profile_view_model.availableArray[index];
                    while (avail) {
                        if (!data) {
                            break;
                        }
                        if (data.ResponseCode != 'WP1008') {
                            Workport.utils.alertMsg("", data.ResponseMessage, function (_data) {
                            });
                        }
                        community_profile_view_model.communityName = $("#community_name").val();
                        var realCB = community_profile_view_model.callbackArray[index];
                        realCB();
                        break;
                    }
                    community_profile_view_model.requestArray.splice(index, 1);
                    community_profile_view_model.callbackArray.splice(index, 1);
                    community_profile_view_model.availableArray.splice(index, 1);
                }
            };
            Workport.CommunityAPI.postCommunityMemberShip(cb, parameter);
        }
    },
    request_join_leave_status: function (communityID, action, controllerCB) {
        var parameter = {
            communityId: '',
            action: ''
        };
        parameter.communityId = communityID;
        parameter.action = action;
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);
        var cb = function (data) {
            var index = $.inArray(req, community_profile_view_model.requestArray);
            if (index >= 0) {
                var avail = community_profile_view_model.availableArray[index];
                while (avail) {
                    if (data.ResponseCode == "WP1008") {
                        community_profile_view_model.isChanged = true;
                        if (action == "1") {
                            $("#communities_profile_display_upload_button").text("Join");
                            if ($.trim($("#community_type").val()) == "Moderated") {
                                $("#skipicon").hide();
                            }
                            Workport.utils.alertMsg("", "You have left the community.", function (_data) {
                                $('#communities_profile').data("kendoWindow").close();
                            });
                        }
                        else if (action == "0") {
                            if ($.trim($("#community_type").val()) == "Moderated") {
                                Workport.utils.alertMsg("", "Your request to join the community is pending with Moderator.", function (_data) {
                                    $('#communities_profile').data("kendoWindow").close();
                                });
                            }
                            else if ($.trim($("#community_type").val()) == "Open") {
                                Workport.utils.alertMsg("", "You have joined the community.", function (_data) {
                                    $('#communities_profile').data("kendoWindow").close();
                                });
                            }
                            $("#communities_profile_display_upload_button").text("Leave");
                            $("#skipicon").show();
                        }
                    }
                    else {
                        Workport.utils.alertMsg(alertTitle, data.ResponseMessage, function (_data) {});
                    }
                    var realCB = community_profile_view_model.callbackArray[index];
                    realCB();
                    break;
                }
                community_profile_view_model.requestArray.splice(index, 1);
                community_profile_view_model.callbackArray.splice(index, 1);
                community_profile_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.CommunityAPI.postMemberShip(cb, parameter);
    },
    request_rss: function (communityID, action, controllerCB) {
        var parameter = {
            communityId: '',
            action: ''
        };
        parameter.communityId = communityID;
        parameter.action = action;
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);
        var cb = function (data) {
            if (data.ResponseCode == "WP1008") {
                if (action == "1") {
                    $("#communities_profile_rss_btn i").removeClass("main_common_rssGrey_10_10").addClass("main_common_rss_10_10").attr('title', 'Unsubscribe');

                } else {
                    $("#communities_profile_rss_btn i").removeClass("main_common_rss_10_10").addClass("main_common_rssGrey_10_10").attr('title', 'Subscribe');
                }
            }else{
                Workport.utils.alertMsg('', data.ResponseMessage, function (_data) {});
            }
        };
        Workport.CommunityAPI.postSubscribe(cb, parameter);
    }
});
kendo.bind($("#communities_profile"), community_profile_view_model);